package com.bwie.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

@Configuration
@Order(1)
public class MyFilter implements GlobalFilter {

    @Autowired
    StringRedisTemplate redisTemplate;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();

        String path = request.getURI().getPath();
        System.out.println("请求路径是"+path);

        if(path.contains("userLogin")){

            System.out.println("登录放行路径"+path);

            return chain.filter(exchange);
        }

        String token = request.getHeaders().getFirst("token");
        Claims claims = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody();
        Integer userId = claims.get("userId", Integer.class);

        if(token==null ||token.isEmpty()){
            System.out.println("token为空禁止访问");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return  response.setComplete();

        }

        String key="token-"+userId;
        String redisToken = redisTemplate.opsForValue().get(key);
        if(redisToken==null){
            System.out.println("token为空");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        if(!redisToken.equals(token)){
            System.out.println("token错误");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //续期15分钟
        redisTemplate.expire(key,15, TimeUnit.MINUTES);

        return chain.filter(exchange);
    }
}
